import api from './config'
import API_CONFIG from './apiConfig.js'
import logger from '../utils/logger.js'

// 团队管理相关API
export const teamApi = {
  /**
   * 创建团队
   * @param {string} teamName - 团队名称（必填）
   * @param {string} teamIntroduction - 团队简介（必填）
   * @param {number} numberLimit - 限制人数（非必填）
   */
  createTeam(teamName, teamIntroduction, numberLimit) {
    logger.log('🏆 [TeamAPI] 调用创建团队接口')
    logger.log('📝 [TeamAPI] 参数:', { teamName, teamIntroduction, numberLimit })
    logger.log('🌐 [TeamAPI] 接口地址:', API_CONFIG.getFullURL('/goc/team/createTeam'))
    
    // 构建请求参数 - 使用后端要求的参数名
    const params = {
      teamName,
      teamIntroduction
    }
    
    // 如果提供了限制人数，添加到参数中
    if (numberLimit !== null && numberLimit !== undefined && numberLimit !== '') {
      params.numberLimit = numberLimit
    }
    
    logger.log('📤 [TeamAPI] 最终请求参数:', params)
    
    return api.post('/goc/team/createTeam', null, { params })
  },

  /**
   * 获取我的团队列表
   */
  getMyTeams() {
    logger.log('📋 [TeamAPI] 调用获取团队列表接口')
    logger.log('🌐 [TeamAPI] 接口地址:', API_CONFIG.getFullURL('/goc/team/findAllTeam'))
    logger.log('🔑 [TeamAPI] JWT令牌会自动添加到请求头中')
    return api.get('/goc/team/findAllTeam')
  },

  /**
   * 获取团队详情
   * @param {string} teamId - 团队ID
   */
  getTeamDetail(teamId) {
    logger.log('🔍 [TeamAPI] 调用获取团队详情接口, teamId:', teamId)
    return api.get(`/goc/team/detail/${teamId}`)
  },

  /**
   * 邀请学生加入团队（单个）
   * @param {string} teamId - 团队ID
   * @param {string} studentId - 学生ID
   */
  inviteStudent(teamId, studentId) {
    logger.log('👨‍🎓 [TeamAPI] 调用邀请学生接口')
    return api.post('/goc/team/inviteStudent', null, {
      params: { teamId, studentId }
    })
  },

  /**
   * 批量邀请学生加入团队
   * @param {string|number} teamId - 团队ID
   * @param {Array<string>} studentAccounts - 学生账号数组
   */
  inviteStudents(teamId, studentAccounts) {
    logger.log('👥 [TeamAPI] 调用批量邀请学生接口')
    logger.log('📝 [TeamAPI] 团队ID (原始):', teamId, typeof teamId)
    logger.log('📝 [TeamAPI] 学生账号列表:', studentAccounts)
    logger.log('🌐 [TeamAPI] 接口地址:', API_CONFIG.getFullURL('/goc/team/inviteStudents'))
    
    // ✅ 学生账号直接保持原始字符串格式，不做任何转换
    // 无论是纯数字账号（如 "1234567"）还是字符串账号（如 "lixin"），都保持原样
    const studentAccountsProcessed = studentAccounts.map(account => {
      const accountStr = String(account).trim()
      logger.log(`🔢 [TeamAPI] 处理账号: "${account}" -> "${accountStr}"`)
      return accountStr
    })
    
    // ⚠️ 重要：teamId 是大数（超过 JavaScript 安全整数范围），必须保持字符串格式
    // 如果转换为 Number 会丢失精度！
    // 例如: "1973372280180445184" -> 1973372280180445200 (精度丢失)
    const teamIdAsString = String(teamId)
    
    logger.log('📤 [TeamAPI] 最终请求参数:', {
      teamId: teamIdAsString,
      studentAccounts: studentAccountsProcessed
    })
    logger.log('✅ [TeamAPI] teamId 和 studentAccounts 都保持原始字符串格式')
    
    return api.post('/goc/team/inviteStudents', {
      teamId: teamIdAsString,                 // teamId 保持字符串格式（大数）
      studentAccounts: studentAccountsProcessed  // studentAccounts 保持原始字符串数组
    })
  },

  /**
   * 删除团队
   * @param {string} teamId - 团队ID
   */
  deleteTeam(teamId) {
    logger.log('🗑️ [TeamAPI] 调用删除团队接口, teamId:', teamId)
    logger.log('🌐 [TeamAPI] 接口地址:', API_CONFIG.getFullURL('/goc/team/deleteTeam'))
    logger.log('📤 [TeamAPI] 请求参数:', { teamId })
    return api.post('/goc/team/deleteTeam', null, {
      params: { teamId }
    })
  },

  /**
   * 更新团队信息
   * @param {string} teamId - 团队ID
   * @param {Object} teamData - 团队数据
   */
  updateTeam(teamId, teamData) {
    logger.log('✏️ [TeamAPI] 调用更新团队接口, teamId:', teamId)
    return api.put(`/goc/team/update/${teamId}`, teamData)
  },

  /**
   * 根据用户ID查询团队
   * @param {string} userId - 用户ID
   */
  findById(userId) {
    logger.log('🔍 [TeamAPI] 调用根据用户ID查询团队接口')
    logger.log('📝 [TeamAPI] 用户ID:', userId)
    logger.log('🌐 [TeamAPI] 接口地址:', API_CONFIG.getFullURL('/goc/team/findById'))
    return api.get('/goc/team/findById', {
      params: { id: userId }
    })
  },

  /**
   * 根据团队ID查询所有学生
   * @param {string|number} teamId - 团队ID
   */
  findAllStuByTeamId(teamId) {
    logger.log('👨‍🎓 [TeamAPI] 调用查询班级学生列表接口')
    logger.log('📝 [TeamAPI] 团队ID (原始):', teamId, '(类型:', typeof teamId, ')')
    logger.log('🌐 [TeamAPI] 接口地址:', API_CONFIG.getFullURL('/goc/team/findAllStuByTeamId'))
    logger.log('📊 [TeamAPI] 请求方法: POST')
    logger.log('📋 [TeamAPI] 参数类型: params')
    
    // teamId可能是大数字，保持字符串格式避免精度丢失
    const teamIdStr = String(teamId)
    logger.log('🔢 [TeamAPI] 处理后的teamId:', teamIdStr, '(字符串格式，保持精度)')
    
    return api.post('/goc/team/findAllStuByTeamId', null, {
      params: { teamId: teamIdStr }
    })
  },

  /**
   * 从团队中删除学生
   * @param {string|number} teamId - 团队ID
   * @param {string} studentId - 学生ID
   */
  deleteStuFromTeam(teamId, studentId) {
    logger.log('🗑️ [TeamAPI] 调用删除学生接口')
    logger.log('📝 [TeamAPI] 团队ID:', teamId, '(类型:', typeof teamId, ')')
    logger.log('📝 [TeamAPI] 学生ID:', studentId, '(类型:', typeof studentId, ')')
    logger.log('🌐 [TeamAPI] 接口地址:', API_CONFIG.getFullURL('/goc/team/deleteStuFromTeam'))
    logger.log('📊 [TeamAPI] 请求方法: GET')
    logger.log('📋 [TeamAPI] 参数类型: params')
    
    // teamId和studentId都保持字符串格式
    const teamIdStr = String(teamId)
    const studentIdStr = String(studentId)
    
    logger.log('📤 [TeamAPI] 最终请求参数:', {
      teamId: teamIdStr,
      studentId: studentIdStr
    })
    
    return api.get('/goc/team/deleteStuFromTeam', {
      params: {
        teamId: teamIdStr,
        studentId: studentIdStr
      }
    })
  }
}

export default teamApi 